package fr.cephb.joperon.swing;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.AbstractAction;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import fr.cephb.joperon.core.Operon;
import fr.cephb.joperon.core.OperonDB;
import fr.cephb.joperon.tool.OperonFactory;

public abstract class OperonFrame
extends JInternalFrame
	{
	private static final long serialVersionUID = 1L;
	private OperonGUI owner;
	protected JPanel content;
	protected OperonFrame(OperonGUI owner,String title)
		{
		super(title,true,true,true,true);
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.owner=owner;
		this.addInternalFrameListener(new InternalFrameAdapter()
			{
			@Override
			public void internalFrameOpened(InternalFrameEvent e) {
				Dimension d=OperonFrame.this.owner.getDesktop().getSize();
				Dimension d2= new Dimension(0,0);
				d2.width=(int)(d.width*0.8);
				d2.height=(int)(d.height*0.8);
				OperonFrame.this.setBounds(
					(int)((d.width-d2.width)*Math.random()),
					(int)((d.height-d2.height)*Math.random()),
					d2.width,
					d2.height
					);
				}
			@Override
			public void internalFrameClosing(InternalFrameEvent e) {
				doMenuClose();
				}
			});
		
		this.content= new JPanel(new BorderLayout());
		this.setContentPane(this.content);
		JMenuBar bar= new JMenuBar();
		setJMenuBar(bar);
		JMenu menu= new JMenu("File");
		bar.add(menu);
		}
	
	public void doMenuClose()
		{
		this.setVisible(false);
		this.dispose();
		}
	
	
	public OperonGUI getOperonGUI() {
		return owner;
		}
	
	public OperonFactory getOperonFactory()
		{
		return getOperonGUI().getOperonFactory();
		}
	
	public Operon getOperon()
		{
		return getOperonFactory().getOperon();
		}
	
	protected void safeClose(OperonDB<?,?> db)
		{
		if(db!=null) try { db.close();} catch(Exception err) { }
		}
	
	private static abstract class ListSelectionListenerAdapter
		implements ListSelectionListener
		{
		AbstractAction act;
		JTable table;
		ListSelectionListenerAdapter(AbstractAction act,JTable table)
			{
			this.act=act;
			this.table=table;
			}
		}
	
	protected void selectionListen(AbstractAction act,JTable table)
		{
		act.setEnabled(table.getSelectedRowCount()==1);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListenerAdapter(act,table)
			{
			@Override
			public void valueChanged(ListSelectionEvent e) {
				this.act.setEnabled(this.table.getSelectedRowCount()==1);
				}
			});
		}
	}
